import {NestFactory} from '@nestjs/core';
import {NestExpressApplication} from '@nestjs/platform-express';
import {AppModule} from './app.module';
import {ConfigService} from "@nestjs/config";
import csurf from 'csurf';
import helmet from 'helmet';
import {Logger} from '@nestjs/common';
import cookieParser from "cookie-parser";

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    // 开启跨区访问
    app.enableCors()
    // web 安全，防常见漏洞
    // 注意： 开发环境如果开启 nest static module 需要将 crossOriginResourcePolicy 设置为 false 否则 静态资源 跨域不可访问
    app.use(helmet({crossOriginOpenerPolicy: {policy: 'same-origin-allow-popups'}, crossOriginResourcePolicy: false}));
    //主要是处理 XSF 工具等 跨站站点请求伪造 之类的攻击
    app.use(cookieParser());
    //防止csrf跨站伪造请求攻击
    // app.use(csurf({cookie: true}));
    const logger = new Logger('HTTP');
    app.use((req, res, next) => {
        // 记录请求信息（排除敏感路径和参数）
        const start = Date.now();
        res.on('finish', () => {
            const duration = Date.now() - start;
            // 忽略健康检查等非敏感接口
            if (!req.path.includes('/health')) {
                logger.log(
                    `${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`,
                    `IP: ${req.ip}`,
                );
            }
        });
        next();
    });
    const config = app.get(ConfigService)
    await app.listen(config.get<number>('app.port') ?? 3000);
}

bootstrap();
